#include "../include/asioContextPool.h"
#include "../include/conf_reader.h"
#include <iostream>
asioContextPool::asioContextPool(){
    int size=std::atoi(conf_reader::get_conf_reader_instance()->get_value_from_key("ioContextPoolSize","3"));
    if(size<=0){
        //至少要有一个io_context
        size=1;
    }
    pool_size=size;
    
    this->_io_context_pool.resize(size);
    this->_work_pool.resize(size);
    this->next_io_contex_index=0;
    for(int i=0;i<size;++i){
        _io_context_pool[i]=std::unique_ptr<io_context>(new io_context());
        _work_pool[i]=std::unique_ptr<work>(new work(*(_io_context_pool[i].get())));
    }
    for(int i=0;i<size;++i){
        _thread_pool.emplace_back([this,i](){
            this->_io_context_pool[i]->run();
        });
    }
    
}

io_context& asioContextPool::get_io_context(){
    next_io_contex_index=(next_io_contex_index+1)%pool_size;

    return *(_io_context_pool[next_io_contex_index].get());
}
void asioContextPool::stop_pool(){
    for(auto &work_item:_work_pool){
        work_item->get_io_context().stop();
        work_item.reset();  //完成work_item的析构，并不会影响io_context的声明周期
    }
    for(auto &thread_item:_thread_pool){
        //线程回收，等待run()的结束后
        thread_item.join();
    }
}

asioContextPool::~asioContextPool(){
    stop_pool();
    std::cout<<"成功析构掉 io_context_pool"<<std::endl;
}